<template>
  <div>
    <div class="person-header">
      <p>
        <el-button type="primary" icon="el-icon-plus" @click="add" v-if="isAddAccess">新增</el-button>
        <el-button type="warning" icon="el-icon-refresh" @click="fush" v-if="isFindAccess">更新</el-button>
        <Input v-model="searchConName1" icon="search" @on-change="handleSearch1" placeholder="请输入姓名搜索..." class="my-input" />
      </p>
      <el-button type="danger" icon="el-icon-delete" @click="removeBatch()" :disabled="userIds.length==0?true:false" v-if="isDeleteAccess">批量删除</el-button>
      <span class="btn btn-success fileinput-button">
          <span>批量添加</span>
          <input type="file" @change="importfxx(this)" v-if="isAddAccess" ref="inputer" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
      </span>
      <p> 
        <el-button type="warning" icon="el-icon-download" @click="outExe" round>下载</el-button>
      </p>
    </div>
    <Table :tableData="editIncellData" :pageSize="pageSize" :pageSizes="pageSizes" :currentPage="currentPage" :isUpdateAccess="isUpdateAccess" :isDeleteAccess="isDeleteAccess" @edit="edit" @delete="deleteUser" @batchSelection="handleBatchSelection"></Table>
    <div class="block">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="pageSizes"
        layout="total, sizes, prev, pager, next, jumper"
        :total="editIncellData.length"
        prev-text="上一页"
        next-text="下一页">
    </el-pagination>
    </div>
    <el-dialog title="新增员工" :visible.sync="dialogFormVisible">
      <el-form :model="form" label-position="left">
        <el-form-item label="工号" :label-width="formLabelWidth">
          <el-input v-model="form.userId" autocomplete="off"  :disabled="userIdLog"></el-input>
        </el-form-item>
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="入职日期" :label-width="formLabelWidth">
          <el-date-picker v-model="form.hiredate" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="入职地" :label-width="formLabelWidth">
          <el-select v-model="form.entryTo" placeholder="请选择入职地">
            <el-option label="南京" value="南京"></el-option>
            <el-option label="深圳" value="深圳"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在城市" :label-width="formLabelWidth">
          <el-input v-model="form.currentCity" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所在项目组" :label-width="formLabelWidth">
          <el-input v-model="form.projectTeam" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出差">
          <el-switch v-model="form.statue"></el-switch>
        </el-form-item>
        <el-form-item label="管理员">
          <el-switch v-model="form.consumee"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="addUser()" v-show="addLog">确 定</el-button>
        <el-button type="primary" @click="editUser()" v-show="editLog">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import axios from 'axios'
  import qs from 'qs'
  import Table from '../components/Table'
  import tableData from '@/settings/table_data.js'
  export default {
    name: "Personal",
    components: {Table},
    data(){
      return {
        //分页
        pageSize: 8,
        pageSizes: [8,10,50,999],
        currentPage: 1,
        userIds: [],//根据工号批量删除
        batchIndexs: [],//批量删除的索引
        searchConName1: '',
        editIncellColumns: [],
        editIncellData: [],
        excelData: [],
        initTable1: [],
        selectedItem: null,
        dialogFormVisible: false,
        addLog: false,
        editLog: false,
        userIdLog: false,
        b:[],
        form: {
          password: '666',
          userId: 1000,
          name: '',
          hiredate: '',
          entryTo: '',
          currentCity: '',
          status: '',
          statue: false,
          consumer: '',
          consumee: false
        },
        // isConsumer: true,
        //权限控制
        isAddAccess: false,
        isDeleteAccess: false,
        isUpdateAccess: false,
        isFindAccess: true,
        formLabelWidth: '120px'
      }
    },
    methods: {
      //更新
      fush () {
        history.go(0)
      },
      //分页
      handleSizeChange (val) {
        this.pageSize = val
      },
      handleCurrentChange (val) {
        this.currentPage = val
      },
      getData() {
        this.editIncellColumns = tableData.editIncellColumns;
      },
      transStatus () {
        return this.form.status = this.form.statue==true?'出差':''
      },
      transConsumer () {
        return this.form.consumer = this.form.consumee==true?'管理员':'一般用户'
      },
      //判断是否为管理员
      // isAdmin () {
      //   // return this.isConsumer = this.$route.params.consumer=="管理员"?true:false
      //   return this.isConsumer = sessionStorage.getItem('_consumer_info_')=="超级管理员"?true:false
      // },
      //取消按钮
      cancel () {
        this.dialogFormVisible = false
        this.form = {password: '666',userId: 1000}
      },
      //新增弹出框
      add () {
        this.dialogFormVisible = true
        this.addLog = true
        this.editLog = false
        this.userIdLog = false
      },
      getUserList ()　{
        axios.get('/users').then((res)=>{
          let _res = res.data;
          if(_res.status=="0"){
            this.editIncellData = this.initTable1 = _res.result.list;
          }else{
            this.editIncellData = [];
          }
        })
      },
      search (data, argumentObj) {
            let res = data;
            let dataClone = data;
            for (let argu in argumentObj) {
                if (argumentObj[argu].length > 0) {
                    res = dataClone.filter(d => {
                        return d[argu].indexOf(argumentObj[argu]) > -1;
                    });
                    dataClone = res;
                }
            }
            return res;
        },
        handleSearch1 () {
            this.editIncellData = this.initTable1;
            this.editIncellData = this.search(this.editIncellData, {name: this.searchConName1});
        },
        //新增员工
        addUser () {2
          this.transStatus()
          this.transConsumer()
          let form = qs.stringify(this.form)
          console.log(form);
          axios.post('/users/addUser',form).then((res)=>{
            if(res.data.status == "0"){
              this.dialogFormVisible = false
              this.getUserList()
              this.$message({
                type: 'success',
                message: '新增员工成功'
              })
            }else if(res.data.status == '2'){
              this.$message({
                type: 'warning',
                message: res.data.msg
              })
            }
          })
        },
        //编辑弹出
        edit (data) {
          if(data.form.consumer=='超级管理员'){
            this.$message.warning('更改无效')
          }else{
            this.dialogFormVisible = data.dialogFormVisible
            this.form = data.form
            this.editLog = true
            this.addLog = false
            this.userIdLog = true
          }
        },
        //修改用户
        editUser () {
          this.transStatus()
          this.transConsumer()
          let form = qs.stringify(this.form)
          axios.post('/users/editUser',form).then((res)=>{
            if(res.data.status == "0"){
              this.dialogFormVisible = false
              this.getUserList()
              this.$message({
                type: 'success',
                message: '修改成功!'
              })
            }else{
              alert("系统异常")
            }
          })
        },
        //删除用户
        deleteUser (data) {
          let id = data._id
          axios.post('/users/deleteUser',{id:id}).then((res=>{
            if(res.data.status == "0"){
              return
            }else{
              alert("系统异常")
            }
          }))
        },
        // 导出
        outExe() {
            this.$confirm('此操作将导出excel文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.excelData = this.editIncellData //你要导出的数据list。
                this.export2Excel()
            }).catch(() => {

            });
        },
        export2Excel() {
            var that = this;
            require.ensure([], () => {
                const { export_json_to_excel } = require('../excel/Export2Excel'); //这里必须使用绝对路径
                const tHeader = ['工号','姓名', '入职日期', '入职地','目前所在城市','所在项目组','状态','用户']; // 导出的表头名
                const filterVal = ['userId','name','hiredate', 'entryTo','currentCity','projectTeam','status','consumer']; // 导出的表头字段名
                const list = that.excelData;
                const data = that.formatJson(filterVal, list);
                let time1,time2 = '';
                export_json_to_excel(tHeader, data, '员工表');// 导出的表格名称，根据需要自己命名
            })
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]))
        },
        //批量导入
        importfxx(obj) {
           let _this = this;
           let inputDOM = this.$refs.inputer;
           // 通过DOM取文件数据
           this.file = event.currentTarget.files[0];
           var rABS = false; //是否将文件读取为二进制字符串
           var f = this.file;
           var reader = new FileReader();
           //if (!FileReader.prototype.readAsBinaryString) {
           FileReader.prototype.readAsBinaryString = function(f) {
               var binary = "";
               var rABS = false; //是否将文件读取为二进制字符串
               var pt = this;
               var wb; //读取完成的数据
               var outdata;
               var reader = new FileReader();
               reader.onload = function(e) {
                   var bytes = new Uint8Array(reader.result);
                   var length = bytes.byteLength;
                   for(var i = 0; i < length; i++) {
                       binary += String.fromCharCode(bytes[i]);
                   }
                   var XLSX = require('xlsx');
                   if(rABS) {
                       wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
                           type: 'base64'
                       });
                   } else {
                       wb = XLSX.read(binary, {
                           type: 'binary'
                       });
                   }
                   outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);//outdata就是你想要的东西
                   this.da = [...outdata]
                   let arr = []
                   this.da.map(v => {
                       let obj = {}
                       obj.userId = v['工号']
                       obj.name = v['姓名']
                       obj.hiredate = v['入职日期']
                       obj.entryTo = v['入职地']
                       obj.currentCity = v['目前所在城市']
                       obj.projectTeam = v['所在项目组']
                       obj.status = v['状态']
                       obj.consumer = v['用户']
                       obj.password = '666'
                       obj.addAccess = false
                       obj.deleteAccess = false
                       obj.updateAccess = false
                       obj.findAccess = true
                       arr.push(obj)
                   })

                   let para = {
                       //withList: JSON.stringify(this.da)
                       staffData: arr
                   }
                   let lotUser = qs.stringify(para)
                   axios.post('/users/addLotUser',para).then((res)=>{
                     if(res.data.status == '0'){
                       _this.getUserList()
                       _this.$message({
                         type: 'success',
                         message: res.data.msg
                       })
                     }else{
                       alert('系统异常')
                     }
                   })
                   _this.$message('请耐心等待导入成功');
               }
               reader.readAsArrayBuffer(f);
           }
           if(rABS) {
               reader.readAsArrayBuffer(f);
           } else {
               reader.readAsBinaryString(f);
           }
       },
       //接收子组件的sels
       handleBatchSelection (sels)　{
         let _this = this
         let initRes =[]
         let initIndexs = []
         sels.forEach((item,index) => {
           _this.editIncellData.forEach((v,i) => {
             if(item.userId == v.userId){
               initIndexs.push(i)
             }
           })
           initRes.push(item.userId)
         })
         _this.userIds = initRes
         _this.batchIndexs = initIndexs
       },
       //批量删除
       removeBatch ()　{
         let userIds = this.userIds
         let batchIndexs = this.batchIndexs
         axios.post('/users/batchDeleteUser',userIds).then((res => {
           if(res.data.status == '0'){ //删除成功后splice该项目
             for (let i=batchIndexs.length-1; i>=0; i--) {
               this.editIncellData.splice(batchIndexs[i],1);
             }
             this.$message({
               type: 'success',
               message: res.data.msg
             })
           }else{
             alert('服务器崩溃！')
           }
         }))
       }
    },
    mounted() {
      //do something after mounting vue instance
      this.getUserList()
      // this.isAdmin();
      this.isAddAccess = sessionStorage.getItem('_isAddAccess_') == "true"?true:false
      this.isDeleteAccess = sessionStorage.getItem('_isDeleteAccess_') == "true"?true:false
      this.isUpdateAccess = sessionStorage.getItem('_isUpdateAccess_') == "true"?true:false
      this.isFindAccess = sessionStorage.getItem('_isFindAccess_') == "true"?true:false
    },
    created() {
      //do something after creating vue instance
      this.getData();
    }
  }
</script>

<style lang="less" scoped>
    @import '../assets/css/common.less';
    @import '../assets/css/table.less';
    .ivu-btn>.ivu-icon {
      line-height: 1.5;
      vertical-align: middle;
      margin-left: -12px;
    }
    .my-input{
      width: 200px;
      margin-bottom: 2px;
      height: 43px;
    }
    // .el-input__inner {
    //   width: 45px;
    // }
    .ivu-input {
      height: 43px;
    }
    #upload{
      background: #fcf8f8;
    }
    .person-header{
      display: flex;
      justify-content: space-between;
    }
    .block{
      margin-top: 8px;
    }
    .fileinput-button {
      position: relative;
      display: inline-block;
      background: #409EFF;
      border: 2px solid #409EFF;
      border-radius: 25px;
      padding: 4px 25px;
      overflow: hidden;
      color: #fff;
      text-decoration: none;
      text-indent: 0;
      line-height: 35px;
    }
    .fileinput-button input{
      position:absolute;
      right: 0px;
      top: 0px;
      opacity: 0;
      -ms-filter: 'alpha(opacity=0)';
      font-size: 200px;
    }
</style>
